﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Gman.Entity.Entities;
using Gman.WebApp.ServiceControllers;
using Gman.WebApp.Models;
using System.Web.Caching;
using System.Web.UI;
using Gman.WebApp.Controllers.Base;

namespace Gman.WebApp.Controllers
{
    public class ServicioController : BaseController
    {
        public List<ServicioBE> ListaServicios = new List<ServicioBE>();
        private List<ProveedorBE> ListaProveedores = new List<ProveedorBE>();
        public List<BienBE> ListaBienes = new List<BienBE>();


        public ActionResult Nuevo(Guid id)
        {
            var cache = new CacheProvider();
            ServicioBE servicio = new ServicioBE();
            var model = new ServicioModel(servicio, ListaServicios);
            model = CargarDropDownList(model);
            model.Action = "nuevo";
            cache.Set(model.ID.Value.ToString(), model);
            model.ToolBar = new ToolBarModel();

            return PartialView(@"~/Views/Servicio/AddEditServicio.cshtml", model);
        }

        public ActionResult Buscar()
        {
            var cache = new CacheProvider();
            ServicioBE servicio = new ServicioBE();
            var model = new ServicioModel(servicio, ListaServicios);
            model = CargarDropDownList(model);
            model.Action = "buscar";
            cache.Set(model.ID.Value.ToString(), model);
            model.ToolBar = new ToolBarModel();

            return View(@"~/Views/Servicio/editar.cshtml", model);
        }

        //public ViewResult Ver(Guid id, Int64? idServicio)
        public ActionResult Ver(Guid id, Int64? idServicio)
        {
            var cache = new CacheProvider();
            ServicioModel model = GetServicioModel(id);
            model.Servicio.IDServicio = idServicio;
            model.Servicio = OperacionServiceController.ObtenerServicio(model.Servicio);
            //model.Servicio.LstProveedores = OperacionServiceController.ListaProveedoresXMaterial(model.Material).ToList();

            if (model.Servicio.IDServicio.HasValue)
            {
                cache.Set(idServicio.Value.ToString(), model.Servicio);
                model.Action = "ver";
            }

            return PartialView(@"~/Views/Servicio/AddEditServicio.cshtml", model);
        }

        public ActionResult Editar(Guid id)
        {
            var cache = new CacheProvider();

            ServicioModel model = GetServicioModel(id);
            cache.Set(model.ID.Value.ToString(), model);
            model.Action = "editar";

            if (model.Servicio.IDServicio != null)
                return PartialView(@"~/Views/Servicio/AddEditServicio.cshtml", model);
            else
                return RedirectToAction("Buscar");
        }
        
        public JsonResult Grabar(Guid id)
        {
            try
            {
                UsuariosBE user = UsuarioActual();
                ServicioModel model = GetServicioModel(id);

                if (model.Action == "nuevo")
                {
                    model.Servicio.UsuReg = user.NomUsu;
                    model.Servicio.TermCnxReg = Environment.MachineName;
                    model.Servicio.EstadoServ = 1;
                    model.Servicio.IDEmp = user.IDEmp;

                    Int64 resultado = OperacionServiceController.RegistrarServicio(model.Servicio);


                    if (resultado == 1)
                    {
                        return AjaxResultSuccess(string.Format("Servicio {0} se guardo exitosamente.", model.Servicio.DescServ));
                    }
                    else
                    {
                        return AjaxResultSuccess(string.Format("No se guardo exitosamente."));
                    }
                }

                if (model.Action == "editar")
                {

                    model.Servicio.UsuMod = user.NomUsu;
                    model.Servicio.TermCnxMod = Environment.MachineName;

                    int resultado = OperacionServiceController.ActualizarServicio(model.Servicio);

                    if (resultado == 1)
                    {
                        return AjaxResultSuccess(string.Format("Servicio {0} se guardo exitosamente.", model.Servicio.DescServ));
                    }

                    else
                    {
                        return AjaxResultSuccess(string.Format("No se guardo exitosamente."));
                    }

                }

                return AjaxResultSuccessNoParam();
            }
            catch (Exception ex)
            {
                return AjaxResultError(ex.Message);
            }
        }

        public ActionResult ListarServicios(Guid id)
        {
            ServicioModel model = GetServicioModel(id);
            UsuariosBE user = UsuarioActual();
            model.Servicio.IDEmp = user.IDEmp;
            model.Servicios.Clear();
            model.Action = "buscar";

            List<ServicioBE> ListaServicios = new List<ServicioBE>();
            ListaServicios = OperacionServiceController.ListarServicios(model.Servicio).ToList();

            foreach (ServicioBE m in ListaServicios)
            {
                model.Servicios.Add(m);
            }

            return PartialView(@"~/Views/Servicio/ListServicio.cshtml", model);
        }

        #region Bienes por Servicio

        public ActionResult LoadAddOrEditBienes(Guid id, Guid? bienGuid)
        {
            var cache = new CacheProvider();

            var servicioModel = GetServicioModel(id);

            servicioModel.Bienes = OperacionServiceController.ListarBien(new BienBE() { IDEmp = servicioModel.Servicio.IDEmp }).ToList();

            return PartialView(@"~/Views/servicio/ListaBienXServicio.cshtml", servicioModel);
        }

        public ActionResult AgregarBien(Guid id, int idBien)
        {
            var cache = new CacheProvider();
            ServicioModel model = GetServicioModel(id);
            List<BienBE> lista = model.Bienes;
            BienBE bien = new BienBE();
            foreach (var item in lista)
            {
                if ( item.IDBien == idBien)
                {
                    if (model.Servicio.LstBienes != null && model.Servicio.LstBienes.Count > 0)
                    {
                        foreach (var b in model.Servicio.LstBienes)
                        {
                            if (b.IDBien == idBien)
                                break;
                            else
                            {
                                bien = item;
                                break;
                            }
                        }
                    }

                    else {
                        bien = item;
                        break;
                    }
                }
            }

            if (model.Servicio.LstBienes == null)
            {
                model.Servicio.LstBienes = ListaBienes;
                model.Servicio.LstBienes.Add(bien);
            }
            else
            {
                if (bien.IDBien != null)
                model.Servicio.LstBienes.Add(bien);
            }


            return PartialView(@"~/Views/Servicio/ListaBienXServicio.cshtml", model);
        }

        public ActionResult QuitarBien(Guid id, int idBien)
        {
            var cache = new CacheProvider();
            ServicioModel model = GetServicioModel(id);
            List<BienBE> lista = model.Bienes;
            BienBE bien = new BienBE();
            foreach (var item in model.Servicio.LstBienes)
            {
                if (item.IDBien == idBien)
                {
                    model.Servicio.LstBienes.Remove(item);
                    break;
                }
            }

            return PartialView(@"~/Views/Servicio/ListaBienXServicio.cshtml", model);
        }

        #endregion

        

       


        private ServicioModel CargarDropDownList(ServicioModel model)
        {
            List<SelectListItem> listTipo = new List<SelectListItem>();
            listTipo.Add(new SelectListItem() { Text = "Seleccione ..", Value = null });
            listTipo.Add(new SelectListItem() { Text = "Preventivo", Value = "1" });
            listTipo.Add(new SelectListItem() { Text = "Correctivo", Value = "2" });
            listTipo.Add(new SelectListItem() { Text = "Implementacion", Value = "3" });
            listTipo.Add(new SelectListItem() { Text = "Cierre", Value = "4" });

            List<SelectListItem> listLinea = new List<SelectListItem>();
            listLinea.Add(new SelectListItem() { Text = "Seleccione ..", Value = null });
            listLinea.Add(new SelectListItem() { Text = "Frio", Value = "1" });
            listLinea.Add(new SelectListItem() { Text = "Aire Acondicionado", Value = "2" });
            listLinea.Add(new SelectListItem() { Text = "Electricos", Value = "3" });
            listLinea.Add(new SelectListItem() { Text = "Seguridad", Value = "4" });

            List<SelectListItem> listCate = new List<SelectListItem>();
            listCate.Add(new SelectListItem() { Text = "Seleccione ..", Value = null });
            listCate.Add(new SelectListItem() { Text = "Equipos", Value = "1" });
            listCate.Add(new SelectListItem() { Text = "Muebles", Value = "2" });
            listCate.Add(new SelectListItem() { Text = "Plataformas", Value = "3" });

            List<SelectListItem> listSubCate = new List<SelectListItem>();
            listSubCate.Add(new SelectListItem() { Text = "Seleccione ..", Value = null });
            listSubCate.Add(new SelectListItem() { Text = "Congeladoras", Value = "1" });
            listSubCate.Add(new SelectListItem() { Text = "Vitrinas", Value = "2" });
            listSubCate.Add(new SelectListItem() { Text = "Tablero de control", Value = "3" });

            model.Tipo = new SelectList(listTipo, "Value", "Text");
            model.Linea = new SelectList(listLinea, "Value", "Text");
            model.Categoria = new SelectList(listCate, "Value", "Text");
            model.SubCategoria = new SelectList(listSubCate, "Value", "Text");

            return model;
        }

        private UsuariosBE UsuarioActual()
        {
            try
            {
                UsuariosBE user = (UsuariosBE)Session["user"];
                return user;
            }
            catch { return null; }
        }

        public ActionResult UpdateField(string fieldName, string fieldValue, Guid id, string setterFormatOptions)
        {
            ServicioModel model = GetServicioModel(id);
            SetterFormatOptions setterFormatOptionsEnum = SetterFormatOptionsHelper.Parse(setterFormatOptions);
            List<KeyValuePair<string, string>> validationList = new List<KeyValuePair<string, string>>();

            var setter = new PropertySetter<ServicioModel>.SetterOptions();
            setter.objectToSet = model;
            setter.property = fieldName;
            setter.val = fieldValue;
            setter.SetterFormatOptions = setterFormatOptionsEnum;
            setter.validationList = validationList;

            object valueWasSet = PropertySetter<ServicioModel>.SetFinalObject(setter);

            validationList.AddRange(new ServicioModelValidator().Validate(model));

            return Json
                (new
                {
                    result = true,
                    PropertyValidationList = validationList
                }
                );
        }

        public ActionResult GetValidation(Guid id)
        {
            ServicioModel model = GetServicioModel(id);
            List<KeyValuePair<string, string>> validationList = new List<KeyValuePair<string, string>>();
            List<KeyValuePair<string, string>> propertyChangeList = new List<KeyValuePair<string, string>>();

            validationList.AddRange(new ServicioModelValidator().Validate(model));

            return Json(new
            {
                PropertyValidationList = validationList,
                PropertyVisibilityList = propertyChangeList
            });
        }

        public ServicioModel GetServicioModel(Guid id)
        {
            var cache = new CacheProvider();

            string key = id.ToString();
            var existingModel = cache.Get(key);
            if (existingModel == null)
            {
                existingModel = new ServicioModel(new ServicioBE(), new List<ServicioBE>());
                cache.Set(key, existingModel);
            }
            return (ServicioModel)existingModel;
        }
    }
}
